package com.health.yb.web.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.health.yb.core.exception.CommonException;
import com.health.yb.core.utils.MapperFactoryUtil;
import com.health.yb.web.bean.common.Response;
import com.health.yb.web.bean.entity.YbType;
import com.health.yb.web.bean.entity.YbUser;
import com.health.yb.web.bean.entity.YbUserInfo;
import com.health.yb.web.bean.req.YbUserAddReq;
import com.health.yb.web.bean.req.YbUserReq;
import com.health.yb.web.mapper.UserInfoMapper;
import com.health.yb.web.mapper.YbTypeMapper;
import com.health.yb.web.mapper.YbUserMapper;
import com.health.yb.web.service.UserInfoService;
import com.health.yb.web.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author rjwang
 * @version 1.0
 * @date 2019/12/17 20:35
 */
@Service
@Transactional(isolation = Isolation.REPEATABLE_READ,rollbackFor = Exception.class)
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, YbUserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public Response addUser(String username) {
        String[] split = username.split(";");
        List<String> strings = new ArrayList<>();
        for (String e1 : split) {
            String s = e1.replaceAll("\\s*", "");
            strings.add(s);
        }
        //查询已经存在的用户
        List<YbUserInfo> ybUserInfos = userInfoMapper.selectList(new LambdaQueryWrapper<YbUserInfo>());
        Set<String> usernames = strings.stream().filter(e -> !ybUserInfos.stream().map(YbUserInfo::getUsername).collect(Collectors.toSet()).contains(e)
        ).collect(Collectors.toSet());
        YbUserInfo.YbUserInfoBuilder builder = YbUserInfo.builder();
        if (CollectionUtil.isNotEmpty(usernames)) {
            List<YbUserInfo> list = new ArrayList<>(usernames.size());
            for (String s : usernames) {
                YbUserInfo userInfo = builder.username(s).build();
                list.add(userInfo);
            }
            this.saveBatch(list);
        }
        return new Response().successWithMsg("添加用户成功");
    }
}
